<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled" :class="{ 'detail-form': isDetail }">
      <template #detail>
        <a-form v-bind="formItemLayout" name="ProjectsForm" ref="formRef">
          <a-row>
						<a-col :span="24">
							<a-form-item label="关联合同" v-bind="validateInfos.contractId" id="ProjectsForm-contractId" name="contractId">
								<a-input v-model:value="formData.contractId" placeholder="自动填充" :disabled="true" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合同编号" v-bind="validateInfos.contractNumber" id="ProjectsForm-contractNumber" name="contractNumber">
								<a-input v-model:value="formData.contractNumber" placeholder="自动填充" :disabled="true" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合同主题" v-bind="validateInfos.contractTheme" id="ProjectsForm-contractTheme" name="contractTheme">
								<template v-if="isDetail">
									<span style="display: inline-block; min-height: 32px; line-height: 32px; padding-left: 11px; background: #fafbfc; border-radius: 4px; width: 100%; color: #222;">{{ formData.contractTheme }}</span>
								</template>
								<template v-else>
									<a-select v-model:value="formData.contractTheme" placeholder="请选择合同主题" @change="onContractThemeChange">
										<a-select-option v-for="item in contractThemeOptions" :key="item.id" :value="item.contractTheme">
											{{ item.contractTheme }}
										</a-select-option>
									</a-select>
								</template>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="项目名字" v-bind="validateInfos.projectName" id="ProjectsForm-projectName" name="projectName">
								<a-input v-model:value="formData.projectName" placeholder="请输入项目名字"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="项目内容" v-bind="validateInfos.projectContent" id="ProjectsForm-projectContent" name="projectContent">
								<a-input v-model:value="formData.projectContent" placeholder="请输入项目内容"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合同金额" v-bind="validateInfos.contractAmount" id="ProjectsForm-contractAmount" name="contractAmount" v-if="!isAdd">
								<template v-if="isDetail || !isAdd">
									<span style="display: inline-block; min-height: 32px; line-height: 32px; padding-left: 11px; background: #fafbfc; border-radius: 4px; width: 100%; color: #222;">{{ formattedContractAmount }}</span>
								</template>
								<template v-else>
									<a-input-number v-model:value="formData.contractAmount" placeholder="请输入合同金额" style="width: 100%" :precision="2" :disabled="true"></a-input-number>
								</template>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="剩余金额" v-bind="validateInfos.remainedAmount" id="ProjectsForm-remainedAmount" name="remainedAmount" v-if="!isAdd">
								<span style="display: inline-block; min-height: 32px; line-height: 32px; padding-left: 11px; background: #fafbfc; border-radius: 4px; width: 100%; color: #222;">{{ formattedRemainedAmount }}</span>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="创建时间" v-bind="validateInfos.createdAt" id="ProjectsForm-createdAt" name="createdAt">
								<a-date-picker placeholder="请选择创建时间"  v-model:value="formData.createdAt" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <div v-if="!isAdd">
      <a-tabs v-model:activeKey="activeKey" animated style="overflow:hidden;">
        <a-tab-pane tab="子项目表" key="subProjects" :forceRender="true">
          <j-vxe-table
            :keep-source="true"
            resizable
            ref="subProjectsTableRef"
            :loading="subProjectsTable.loading"
            :columns="subProjectsTable.columns"
            :dataSource="subProjectsTable.dataSource"
            :height="340"
            :disabled="disabled"
            :rowNumber="true"
            :rowSelection="true"
            :toolbar="true"
            :addBtnCfg="subProjectsTable.addBtnCfg"/>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { querySubProjectsListByMainId, queryDataById, saveOrUpdate, updateSubProject, getApprovedContracts } from '../Projects.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {subProjectsColumns} from '../Projects.data';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form, message } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "ProjectsForm",
    components:{
      JVxeTable,
			JFormContainer,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true },
      isDetail: { type: Boolean, default: false },
      isAdd: { type: Boolean, default: false } // 新增 isAdd 标志
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const formRef = ref();
      const subProjectsTableRef = ref();
      // 调试 isAdd
      // console.log('isAdd', props.isAdd);
      const isAdd = computed(() => props.isAdd);
      const subProjectsTable = reactive<Record<string, any>>({
        loading: false,
        columns: subProjectsColumns,
        dataSource: [],
        addBtnCfg: {
          enabled: false, // 编辑弹框时隐藏新增按钮
          buttonIcon: 'ant-design:edit-outlined',
          buttonName: '新增',
          onClick: () => {
            const selectedRows = subProjectsTableRef.value?.getSelectedRows();
            if (selectedRows && selectedRows.length > 0) {
              handleModifySubProject(selectedRows[0]);
            } else {
              message.warning('请先选择一个子项目');
            }
          }
        }
      });
      const activeKey = ref('subProjects');
      const formData = reactive<Record<string, any>>({
        id: '',
        contractId: '',   
        contractNumber: '',   
        contractTheme: '',   
        projectName: '',   
        projectContent: '',   
        contractAmount: null,   
        remainedAmount: null,
        createdAt: '',   
      });

      //表单验证
      const validatorRules = reactive({
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      const contractThemeOptions = ref<any[]>([]);
      // 获取合同主题下拉数据
      async function fetchContractThemes() {
        const res = await getApprovedContracts({});
        console.log('获取合同数据:', res);
        contractThemeOptions.value = Array.isArray(res) ? res : (res?.result || res?.data || []);

        // 打印第一个合同的结构，查看是否有 amount 字段
        if (contractThemeOptions.value.length > 0) {
          console.log('合同数据结构示例:', contractThemeOptions.value[0]);
        }
      }
      // 合同主题变更时自动填充关联合同和合同编号
      function onContractThemeChange(value) {
        const selected = contractThemeOptions.value.find(item => item.contractTheme === value);
        if (selected) {
          formData.contractId = selected.id;
          formData.contractNumber = selected.contractNumber;
          
          // 设置合同金额 - 尝试几种可能的字段名
          const amountValue = selected.amount || selected.contractAmount || selected.money || selected.totalAmount || null;
          if (amountValue !== undefined && amountValue !== null) {
            console.log('设置合同金额:', amountValue);
            formData.contractAmount = parseFloat(amountValue);
          }
        } else {
          formData.contractId = '';
          formData.contractNumber = '';
          formData.contractAmount = null;
        }
      }

      // 修改子项目的处理函数
      function handleModifySubProject(row) {
        if (!row) {
          message.warning('请选择一条记录进行修改');
          return;
        }
        
        // 获取选中行的数据
        const selectedRow = row;
        
        // 打开修改对话框
        const subProjectName = prompt('请输入子项目名称', selectedRow.subProjectName);
        if (subProjectName === null) return; // 用户取消
        
        const subProjectContent = prompt('请输入子项目内容', selectedRow.subProjectContent);
        if (subProjectContent === null) return; // 用户取消
        
        // 获取子项目金额
        const subProjectAmountStr = prompt('请输入子项目金额', selectedRow.subProjectAmount || '0.00');
        if (subProjectAmountStr === null) return; // 用户取消
        
        // 转换为浮点数
        let subProjectAmount = 0;
        try {
          subProjectAmount = parseFloat(subProjectAmountStr);
          if (isNaN(subProjectAmount)) {
            subProjectAmount = 0;
          }
        } catch (e) {
          subProjectAmount = 0;
        }
        
        // 更新数据
        const updatedData = {
          id: selectedRow.id,
          projectId: selectedRow.projectId || formData.id,
          subProjectName,
          subProjectContent,
          subProjectAmount
        };
        
        // 调用API更新数据
        updateSubProject(updatedData).then(res => {
          message.success('修改成功');
          // 刷新子项目列表
          if (formData.id) {
            querySubProjectsListByMainId(formData.id).then(data => {
              subProjectsTable.dataSource = [...data];
            });
          }
        }).catch(err => {
          message.error('修改失败: ' + (err.message || '未知错误'));
        });
      }

      function add() {
        resetFields();
        formData.contractAmount = null; // 新增时合同金额为null
        formData.remainedAmount = null; // 新增时剩余金额为null
        subProjectsTable.dataSource = [];
        subProjectsTable.addBtnCfg.enabled = true;
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const subProjectsDataList = await querySubProjectsListByMainId(row['id']);
        subProjectsTable.dataSource = [...subProjectsDataList];
        subProjectsTable.addBtnCfg.enabled = true; // 编辑时也允许新增子项目
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'subProjects': subProjectsTableRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch (error: any) {
          const errorFields = error?.errorFields;
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        let values = Object.assign({}, dbData, mainData);
        
        // 只有在非新增模式下才获取子表数据
        if (!isAdd.value) {
          const subData = await getSubFormAndTableData();
          values = Object.assign(values, subData);
        }
        
        // 确保合同金额被正确传递
        if (values.contractAmount === undefined || values.contractAmount === null) {
          // 如果没有设置合同金额，尝试从选中的合同中获取
          const selectedContract = contractThemeOptions.value.find(item => item.contractTheme === values.contractTheme);
          if (selectedContract) {
            const amountValue = selectedContract.amount || selectedContract.contractAmount || selectedContract.money || selectedContract.totalAmount;
            if (amountValue !== undefined && amountValue !== null) {
              values.contractAmount = parseFloat(amountValue);
            }
          }
        }
        
        const isUpdate = values.id ? true : false;
        
        // 详细输出准备传给后端的数据
        console.log('==================== 准备传给后端的数据 ====================');
        console.log('操作类型:', isUpdate ? '更新' : '新增');
        console.log('API 端点:', isUpdate ? '/projects/projects/edit' : '/projects/projects/add');
        console.log('数据详情:');
        console.log(JSON.stringify(values, null, 2));
        console.log('合同金额:', values.contractAmount);
        console.log('===========================================================');
        
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      // 格式化合同金额显示
      const formattedContractAmount = computed(() => {
        if (formData.contractAmount === null || formData.contractAmount === undefined) {
          return '-';
        }
        return formData.contractAmount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      });

      // 格式化剩余金额显示
      const formattedRemainedAmount = computed(() => {
        if (formData.remainedAmount === null || formData.remainedAmount === undefined) {
          return '-';
        }
        return formData.remainedAmount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      });

      onMounted(() => {
        if (subProjectsTableRef.value) {
          subProjectsTableRef.value.$on?.('add-row', (row) => {
            // 修改按钮点击事件，获取选中行并进行修改
            const selectedRows = subProjectsTableRef.value?.getSelectedRows();
            if (selectedRows && selectedRows.length > 0) {
              handleModifySubProject(selectedRows[0]);
            } else {
              message.warning('请先选择一个子项目');
            }
          });
        }
        fetchContractThemes();
      });

      return {
        subProjectsTableRef,
        subProjectsTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        contractThemeOptions,
        onContractThemeChange,
        isDetail: props.isDetail, // 暴露 isDetail 给模板
        isAdd, // 规范 isAdd 用法
        handleModifySubProject,
        formattedContractAmount, // 添加格式化的合同金额
        formattedRemainedAmount // 添加格式化的剩余金额
      }
    }
  });
</script>
<style lang="less" scoped>
  .ant-tabs-tabpane.sub-one-form {
    max-height: 340px;
    overflow: auto;
  }
  /* 只在详情表单隐藏 × 和下拉箭头 */
  .detail-form {
    .ant-input-clear-icon,
    .ant-select-clear {
      display: none !important;
    }
    // 彻底隐藏 select 下拉箭头（兜底方案）
    :deep(.ant-select .ant-select-arrow),
    :deep(.ant-select .ant-select-arrow svg),
    :deep(.ant-select .anticon),
    :deep(.ant-select .anticon svg),
    :deep(.ant-select .ant-select-selector svg),
    :deep(.ant-select .ant-select-selector .anticon),
    :deep(.ant-select .ant-select-selector .anticon svg),
    :deep(.ant-select-disabled .ant-select-arrow),
    :deep(.ant-select-disabled .anticon),
    :deep(.ant-select-disabled .anticon svg),
    :deep(.ant-select-disabled .ant-select-selector svg),
    :deep(.ant-select-disabled .ant-select-selector .anticon),
    :deep(.ant-select-disabled .ant-select-selector .anticon svg) {
      display: none !important;
      opacity: 0 !important;
      width: 0 !important;
      height: 0 !important;
      pointer-events: none !important;
      background: none !important;
      color: transparent !important;
    }
  }
</style>
